# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "generic/ubuntu2204"
  memory = 8192
  cpus = 4

  config.vm.provider :virtualbox do |v|
    v.memory = memory
    v.cpus = cpus
  end

  config.vm.provider :libvirt do |v|
    v.memory = memory
    v.cpus = cpus
  end

  if File.exist?("./ssh-config")
    config.ssh.config = "./ssh-config"
  end

  config.vm.synced_folder ".", "/vagrant"

  config.vm.provision "install-dependencies", type: "shell", run: "once" do |sh|
    sh.inline = <<~SHELL
      set -euxo pipefail

      # Use a non-localhost DNS to avoid cluster DNS lookup loops
      echo "nameserver 8.8.8.8" > /etc/resolv.conf

      # Install Go
      GO_VERSION=$(curl -sSfL "https://go.dev/VERSION?m=text" | head -n1)
      curl -sSfL -o- https://go.dev/dl/$GO_VERSION.linux-amd64.tar.gz |
        tar xfz - -C /usr/local

      # Kubernetes
      KUBERNETES_VERSION=v1.34
      curl -fsSL https://pkgs.k8s.io/core:/stable:/$KUBERNETES_VERSION/deb/Release.key | gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
      echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/$KUBERNETES_VERSION/deb/ /" | tee /etc/apt/sources.list.d/kubernetes.list
      curl -fsSL https://download.opensuse.org/repositories/isv:/cri-o:/prerelease:/main/deb/Release.key | gpg --dearmor -o /etc/apt/keyrings/cri-o-apt-keyring.gpg
      echo "deb [signed-by=/etc/apt/keyrings/cri-o-apt-keyring.gpg] https://download.opensuse.org/repositories/isv:/cri-o:/prerelease:/main/deb/ /" | tee /etc/apt/sources.list.d/cri-o.list
      apt-get update
      apt-get install -y \
        build-essential \
        cri-o \
        kubelet \
        kubeadm \
        kubectl \
        podman \
        jq \
        moreutils \
        apparmor \
        apparmor-utils

      # Load the prebuilt container image
      podman load -i /vagrant/image.tar

      # Baseprofile recording requires cosign
      COSIGN_VERSION=v2.4.1
      COSIGN_BINARY=/usr/bin/cosign
      curl -sSfL --retry 5 --retry-delay 3 "https://github.com/sigstore/cosign/releases/download/$COSIGN_VERSION/cosign-linux-amd64" -o "$COSIGN_BINARY"
      chmod +x "$COSIGN_BINARY"

      # Setup CNI to disable IPv6
      CNI_CONFIG=/etc/cni/net.d/10-crio-bridge.conflist
      jq 'del(.plugins[0].ipam.routes[1], .plugins[0].ipam.ranges[1])' $CNI_CONFIG.disabled >$CNI_CONFIG

      # Setup CRI-O
      systemctl enable --now crio

      # Disable kernel print rate limiting for syslog messaging
      sysctl -w kernel.printk_ratelimit=0
      sysctl -w kernel.printk_ratelimit_burst=0

      /vagrant/hack/ci/install-kubernetes.sh
    SHELL
  end
end
